package club.ruanx.movie.controller;

import club.ruanx.bean.PageBean;
import club.ruanx.core.exception.TargetEntityNotFound;
import club.ruanx.movie.entity.News;
import club.ruanx.movie.param.NewsParam;
import club.ruanx.movie.service.NewsService;
import club.ruanx.util.PagingUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * @author 阮胜
 * @date 2018/11/11 19:55
 */
@RestController
@RequestMapping("/news")
@Slf4j
public class NewsController {
    private final NewsService newsService;

    public NewsController(NewsService newsService) {
        this.newsService = newsService;
    }

    @GetMapping("/{id}")
    public News findById(@PathVariable String id) throws TargetEntityNotFound {
        return newsService.findById(id);
    }

    @GetMapping("/list")
    public List<News> list(PageBean pageBean) {
        Page<News> newsPage = newsService.findAll(pageBean.toPageable());
        PagingUtils.setNgxAdminPagingHeader(newsPage.getTotalElements());
        return newsPage.getContent();
    }

    @GetMapping("/last")
    public News last() throws TargetEntityNotFound {
        return newsService.findTop1();
    }

    @PostMapping("/save")
    public News save(@RequestBody @Valid NewsParam newsParam) throws Exception {
        return newsService.saveParam(newsParam);
    }

    @DeleteMapping("/delete/{id}")
    public void delete(@PathVariable String id) throws Exception {
        newsService.delete(id);
    }

    @DeleteMapping("/delete")
    public List<String> deleteAll(String[] ids) {
        return newsService.deleteIn(ids);
    }
}
